package app.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import siotwx.dao.WechattokenDao;
import siotwx.entity.Wechattoken;
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
@Service("WechatService")
public class WechatService {
	public class Token{
		private boolean is_can;
		private String token;
		public Token(){}
		
		public Token(boolean is_can, String token) {
			this.is_can = is_can;
			this.token = token;
		}

		public boolean is_can() {
			return is_can;
		}
		public void setIs_can(boolean is_can) {
			this.is_can = is_can;
		}
		public String getToken() {
			return token;
		}
		public void setToken(String token) {
			this.token = token;
		}
		
	}
	
	@Autowired
	@Qualifier("WechattokenDao")
	private WechattokenDao wechattokenDao;
	
	//获取当前系统中存在的可用的
	@Transactional(readOnly=true)
	public Token getToken(){
		Wechattoken token = wechattokenDao.token();
		if (token!=null) {
			if (token.getExpiresDatetime()>System.currentTimeMillis()+5L*60*1000) {
				return new Token(true,token.getToken());
			}
		}
		return new Token(false, "");
	}
	
	//写入新的token
	public int addToken(String applyUserid,Integer expiresIn,String token,String type){
		long applyDatetime=System.currentTimeMillis();
		long expiresDatetime=applyDatetime+expiresIn*1000L;
		wechattokenDao.insert(new Wechattoken(null, applyDatetime, applyUserid, expiresDatetime, expiresIn, token, type));
		
		return 0;
	}
}
